package com.shootforthestars;

import org.newdawn.slick.Color;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Input;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.geom.Rectangle;
import org.newdawn.slick.geom.Shape;

import com.shootforthestars.core.Actor;
import com.shootforthestars.objects.ObstacleSystem;
import com.shootforthestars.objects.Rocket;

/**
 * @author jmcomets
 */
public class World implements Actor {
	private static final float DEFAULT_HEIGHT = 5000;
	private static final float DEFAULT_WIDTH = 500;
	private Rectangle box;
	private Rocket rocket;
	private ObstacleSystem obstacles;

	public World() {
		this.box = new Rectangle(-DEFAULT_WIDTH / 2, -DEFAULT_HEIGHT,
				DEFAULT_WIDTH, DEFAULT_HEIGHT);
		this.rocket = new Rocket();
		obstacles = new ObstacleSystem(rocket);
	}

	public World(float width, float height) {
		this.box = new Rectangle(-width / 2, -height, width, height);
		this.rocket = new Rocket();
		obstacles = new ObstacleSystem(rocket);
	}

	@Override
	public void init() throws SlickException {
		obstacles.init();
		rocket.init();
	}

	@Override
	public void render(Graphics graphics) throws SlickException {
		graphics.pushTransform();

		// Draw rocket
		rocket.render(graphics);

		// Draw obstacles
		obstacles.render(graphics);

		// Draw outline
		graphics.setColor(Color.cyan);
		graphics.setLineWidth(1.5f);
		graphics.draw(box);

		graphics.popTransform();
	}

	@Override
	public void update(Input input, int delta) throws SlickException {
		// Update the rocket
		rocket.update(input, delta);

		// Keep rocket from going out of the screen (x-axis)
		Shape rocketShape = rocket.getCollisionComponent().getShape();
		float boxWidth = box.getWidth();
		if (rocketShape.getMaxX() > boxWidth / 2) {
			rocketShape.setX(boxWidth / 2 - rocketShape.getWidth());
		} else if (rocketShape.getMinX() < -boxWidth / 2) {
			rocketShape.setX(-boxWidth / 2);
		}

		// Update the obstacles
		obstacles.update(input, delta);
	}

	public boolean isFinished() {
		return rocket.getCollisionComponent().getShape().getMaxY() > box.getHeight();
	}

	public boolean isGameOver() {
		return rocket.getCollisionComponent().getShape().getMaxY() > 0
				|| rocket.getLifeComponent().isAlive() == false;
	}
	
	public ObstacleSystem getObstacleSystem() {
		return obstacles;
	}

	public Rocket getRocket() {
		return rocket;
	}
}
